#include "powerup.h"
#include "datafun.h"
#include "random_gen.h"
#include "rockdodger_globals.h"

static short max_surf_laserpowerup;	//!< number of available surfaces
static short max_surf_shieldpowerup;	//!< number of available surfaces

SDL_Surface *surf_laserpowerup[MAX_POWERUP_IMAGES];	//!< SDL Surfaces for the laser powerup 
SDL_Surface *surf_shieldpowerup[MAX_POWERUP_IMAGES];	//!< SDL Surfaces for the shield powerup

struct powerup powerup;

struct powerup *init_powerup() {
  int i;
  char name[128];

  //laserpowerup: load images and set color key for transparency
  printf("Laserpowerups ");
  for(i = 0; i < MAX_POWERUP_IMAGES; ++i) {
    sprintf(name, "laserpowerup.%02X.png", i);
    if((surf_laserpowerup[i] = load_image(name, 0, 0, 255)) == NULL)
      break;
    printf("$%02x ", i);
  }
  puts("were loaded.");
  max_surf_laserpowerup = i;
  printf("Shieldpowerups ");
  //shieldpowerup: load image and set color key for transparency
  for(i = 0; i < MAX_POWERUP_IMAGES; ++i) {
    sprintf(name, "shieldpowerup.%02X.png", i);
    if((surf_shieldpowerup[i] = load_image(name, 0, 0, 255)) == NULL)
      break;
    printf("$%02x ", i);
  }
  puts("were loaded.");
  max_surf_shieldpowerup = i;
  if(max_surf_laserpowerup == 0 || max_surf_shieldpowerup == 0)
    return NULL;
  deactivate_powerup();
  return &powerup;
}

void display_powerup(SDL_Surface * surf_screen) {
  static SDL_Rect dest;
  SDL_Surface *powersurf = powerup.surf[powerup.img_ctr++];

  dest.w = powersurf->w;
  dest.h = powersurf->h;
  dest.x = powerup.x;
  dest.y = powerup.y;
  SDL_BlitSurface(powersurf, NULL, surf_screen, &dest);
  if(powerup.surf == surf_laserpowerup) {
    if(powerup.img_ctr >= max_surf_laserpowerup)
      powerup.img_ctr = 0;
  } else if(powerup.surf == surf_shieldpowerup) {
    if(powerup.img_ctr >= max_surf_shieldpowerup)
      powerup.img_ctr = 0;
  } else {			//Just in case
    powerup.img_ctr = 0;
  }
}

void deactivate_powerup() {
  powerup.active = 0;
  powerup.countdown = POWERUPDELAY;
  powerup.img_ctr = 0;
}

void update_powerup() {
  if(powerup.active) {
    SDL_Surface *surf = powerup.surf[powerup.img_ctr];
    powerup.x += powerup.dx * movementrate;
    powerup.y += powerup.dy * movementrate;
    if(powerup.x < -surf->w
       || powerup.y < -surf->h
       || powerup.x > xsize
       || powerup.y > ysize) {
      deactivate_powerup();
    }
  } else {
    powerup.countdown -= movementrate;
    if(powerup.countdown < 0 && rnd() < .3) {
      powerup.active = 1;
      powerup.x = xsize;
      powerup.dx = -(3 + rnd() * 5);
      powerup.dy = .5 + rnd() * 3;
      if((powerup.y = rnd() * ysize) >= ysize / 2)
	powerup.dy = -powerup.dy;
      if(rnd() < .7) {
	powerup.surf = surf_laserpowerup;
      } else {
	powerup.surf = surf_shieldpowerup;
      }
    }
  }
}
